
package iautils;

import imganalysis.BIC;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

/**
 *
 * @author sheila
 */
 public class IAUtils {
     public IAUtils(){
     }
    public static void printArrayIntegers(int [] pai){
        for (int j = 0; j < pai.length; j++) {
            System.out.print(" - "+pai[j]);
        }
        System.out.println("\n");
    }

    public static int compareHistograms(int [] HistogramLog1, int [] HistogramLog2){
        int distance=0;
        for (int i = 0; i < HistogramLog2.length; i++) {
            distance += Math.abs( HistogramLog1[i] - HistogramLog2[i] );
        }
        return distance;
    }

    public static void loadAllImagesIntoHistograms(ArrayList <int []> paiHistograms){
        try{

            FileInputStream fstream = new FileInputStream("/home/sheila/images_databases/corelnames.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            for(int i=0; (strLine = br.readLine()) != null; i++) {
                //System.out.println (strLine);
                PlanarImage pi = JAI.create("fileload", strLine);
                BIC oBIC=new BIC(pi);
                paiHistograms.add(  getLogarithmicHistogram(oBIC.getHistogram())  );
            }
            in.close();
            writeAllHistograms(paiHistograms);
        }catch (Exception e){   System.err.println("Error: " + e.getMessage());    }
    }

    public static int[] getLogarithmicHistogram(int[] aiHistogram){
        for (int i = 0; i < aiHistogram.length; i++) {
            aiHistogram[i] =  (int)getLogarithmicFunction (aiHistogram[i]);
        }
        return aiHistogram;
    }

    public static double getLogarithmicFunction(int x){
        if(x==0) return 0;
        else if( x>0 && x<=1 ) return 1;
        else return Math.ceil(  Math.log(x)/Math.log(2) ) + 1;// with base change
    }

    public static void writeAllHistograms(ArrayList<int[]> paiHistograms){
        try{
            FileWriter fstream = new FileWriter("AllHistograms.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i = 0; i < paiHistograms.size(); i++){
                StringBuffer strb=new StringBuffer();
                strb.append(i);
                strb.append("\t");
                int [] iHistogram = paiHistograms.get(i);
                for (int bin = 0; bin < iHistogram.length; bin++) {
                    strb.append(  iHistogram[bin]  );
                    strb.append(" ");
                }
                out.write(strb+"\n");
            }
            out.close();
        }catch (Exception e){ System.err.println("Error: " + e.getMessage());  }
    }
    /*
     * This function carries all the Feature Vectors.
     */
    public static ArrayList<int[]> readHistograms(String path) {
        try{
            ArrayList<int[]> paiHistograms=new ArrayList<int []>();
            FileInputStream fstream = new FileInputStream(path);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            for(int i=0; (strLine = br.readLine()) != null; i++) {
                strLine=strLine.substring(strLine.lastIndexOf("\t")+1);
                int[] aiHistogram=new int[128];
                String [] strHistogram=strLine.split(" ");
                for (int j = 0; j < strHistogram.length; j++) {
                    aiHistogram[j] = Integer.parseInt(strHistogram[j]);
                }
                paiHistograms.add(aiHistogram);
            }
            in.close();
            return paiHistograms;

        }catch (Exception e){   System.err.println("Error: " + e.getMessage());    }
        return null;
    }


        public static String readLineFromImagesFile(int iLine){
        String strLine="";
        try{
            FileInputStream fstream = new FileInputStream("/home/sheila/images_databases/corelnames.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            for(int i=0; i<iLine && (br.readLine()) != null; i++) ;
            strLine = br.readLine();
            in.close();
        }catch (Exception e){   System.err.println("Error: " + e.getMessage());    }
        return strLine;
    }

    public static int searchIdImageByPath(String imgPath, String imagesPaths){
        try{
            FileInputStream fstream = new FileInputStream(imagesPaths);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String tmpPath=br.readLine();
            for(int i=0; tmpPath!= null; i++){ //
                if (imgPath.compareTo(tmpPath)==0){
                    in.close();
                    return i;
                }
                tmpPath=br.readLine();
            }
            in.close();
        }catch (Exception e){   System.err.println("Error: " + e.getMessage());    }
        return -1;
    }

//    public static void getSimilarImages(ArrayList <int[]> paiHistograms){
//      PlanarImage pi = JAI.create("fileload", "/home/sheila/images_databases/corel/A8740/A8798.ppm");
//      BIC oBIC=new BIC(pi);
//      int[] imgQuery = getLogarithmicHistogram(oBIC.getHistogram());
//      int minimun=10000,distance=0,nearerIndex=0;
//      int i=0;
//
//      for ( i = 0; i < paiHistograms.size(); i++) {
//            distance = compareHistograms(imgQuery,paiHistograms.get(i));
//            //System.out.println("i:"+i +" - distance:"+distance);
//            if( distance < minimun){
//                minimun=distance;
//                nearerIndex=i;
//            }
//       }
//        System.out.println("La mas cercana tem o index i  "+nearerIndex +" with a distance of: "+ minimun);
//        //this.printHistogram(aiHistograms.get(i));
//    }

}
